package com.fatsatsuma.email;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

/**
 * @author $Id: HtmlUtils.java,v 1.3 2006/11/21 16:35:58 gevans Exp $
 */
public class HtmlUtils {

	private static Logger log = Logger.getLogger(HtmlUtils.class);

	private static final String IMAGES_STARTTAG = "<img ";

	private static final String SRC_STARTTAG = "src=\"";

	private static final String ALT_STARTTAG = "alt=\"";

	private static final String END_QUOTE = "\"";

	public static List<ImageSummary> getDistinctImageReferences(StringBuffer stringBuffer,
			String basePath) {
		List<ImageSummary> imageReferences = new ArrayList<ImageSummary>();
		int startLocation = 0;
		int nextIndex = 0;

		while ((nextIndex = stringBuffer.indexOf(IMAGES_STARTTAG, startLocation)) != -1) {
			if (log.isDebugEnabled()) {
				log.debug("found @ " + nextIndex);
			}
			startLocation = nextIndex + IMAGES_STARTTAG.length();
			int startIndex = stringBuffer.indexOf(SRC_STARTTAG, startLocation) + SRC_STARTTAG.length();
			int endIndex = stringBuffer.indexOf(END_QUOTE, (startIndex));
			if (log.isDebugEnabled()) {
				log.debug(startIndex + "->" + endIndex);
			}

			ImageSummary imageSummary = new ImageSummary();
			String imageReference = stringBuffer.substring(startIndex, endIndex);

			imageSummary.setReference(imageReference);
			imageSummary.setSource(containsFullReference(imageReference) ? imageReference
					: (basePath + imageReference));

			// the alternative text tag will be within the following boundaries
			// startLocation -> next &gt; tag
			int nextGreaterThanTag = stringBuffer.indexOf(">", startLocation);
			if (log.isDebugEnabled()) {
				log.debug("Alt Between " + startLocation + "->" + nextGreaterThanTag);
			}

			int startAlttag = stringBuffer.indexOf(ALT_STARTTAG, startLocation);
			if (startAlttag == -1) {
				imageSummary.setAlternativeText("");
			} else if (startAlttag > nextGreaterThanTag) {
				imageSummary.setAlternativeText("");
			} else {
				startAlttag += ALT_STARTTAG.length();
				imageSummary.setAlternativeText(stringBuffer.substring(startAlttag, stringBuffer.indexOf(
						END_QUOTE, startAlttag)));
			}

			imageReferences.add(imageSummary);
		}

		return imageReferences;
	}

	public static boolean containsFullReference(String input) {
		return input.contains("http://") || input.contains("https://");
	}

	public static String getPageAsString(String url) throws WebRequestFailedException {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		try {
			client.executeMethod(method);
			return method.getResponseBodyAsString();
		} catch (IOException exp) {
			log.error("Failed to get url " + url, exp);
			throw new WebRequestFailedException(url, exp);
		}
	}
}
